<?php

namespace app\admin\controller\usermanage;

use app\admin\model\share\Share;
use app\admin\model\usermanage\IntegralLog;
use app\api\model\Register;
use app\common\controller\Backend;
use fast\Random;
use fast\Security;
use think\Db;
use think\Validate;
use app\admin\model\usermanage\Users as UsersModel;
use app\admin\model\usermanage\UsersGroup as UsersGroupModel;
use app\admin\model\usermanage\GroupPv as GroupPvModel;

/**
 * 用户
 *
 * @icon fa fa-users
 */
class Users extends Backend
{

    /**
     * Users模型对象
     * @var \app\admin\model\usermanage\Users
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\usermanage\Users;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $k=> $row) {
                $group = UsersGroupModel::get($row['group_id']);
                $list[$k]['group_name'] = $group?$group->group_name:'';
                if ($row['parent_id']){
                    $parent = UsersModel::get($row['parent_id']);
                    $list[$k]['parent_name'] = $parent?$parent->realname:'';
                } else {
                    $list[$k]['parent_name'] = '';
                }

                if ($row['contact_id']){
                    $contact= UsersModel::get($row['contact_id']);
                    $list[$k]['contact_name'] = $contact?$contact->realname:'';
                } else {
                    $list[$k]['contact_name'] = '';
                }
                $row->visible(['id','account','parent_name','contact_name','createtime','total_price','price','realname','is_distributor','group_name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function addGroup($user_id,$type=0){
        $group_model = new UsersGroupModel();
        $group_model->setAttr('type',$type);
        $group_model->user_id = $user_id;
        if ($type==0){
            $group_model->group_name = 'A1';
        } else {
            $group_model->group_name = 'B1';
        }
        $group_model->save();
        return $group_model->id;
    }

    public function getAccount()
    {
        $account = null;
        while (true) {
            $account = 'z'.rand(1000000,9999999);
            $exist_order_no = UsersModel::where(['account' => $account])->find();
            if (!$exist_order_no) {
                break;
            }
        }
        return $account;
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            //$this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $exist_account = UsersModel::where([
                        'account' => $params['account'],
                    ])->find();

                    if ($exist_account){
                        exception(__("账号已存在请刷新页面重新添加"));
                    }
                    if (!Validate::is($params['password'], '\S{6,30}')) {
                        exception(__("Please input correct password"));
                    }
                    if (!Validate::is($params['binding'], '1[3-9]\d{9}')) {
                        exception(__("请输入正确的手机号"));
                    }
                    $exist_binding = UsersModel::where([
                        'binding' => $params['binding'],
                    ])->find();

                    if ($exist_binding){
                        exception(__("手机号已存在"));
                    }
                    $security = new Security();
                    //$params['salt'] = Random::alnum();
                    //$params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
                    $params['username'] =  $params['account'];
                    $params['avatar_url'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $params['password'] = $security->generatePasswordHash($params['password'], 5);
                    $params['pay_pwd'] = $security->generatePasswordHash('123456', 5);
                    $params['is_admin'] = 1;
                    $params['is_distributor'] = 1;
                    $params['is_register'] = 1;
                    $params['register_auth_time'] = time();
                    $params['time'] = time();

                    $result = $this->model->save($params);

                    if ($result === false) {
                        exception($this->model->getError());
                    }

                    $first_group_id = $this->addGroup($this->model->id,0);
                    $new_group_id = $this->addGroup($this->model->id,1);

                    $group_pv = new GroupPvModel();

                    $group_pv->first_group_id = $first_group_id;
                    $group_pv->new_group_id = $new_group_id;
                    $group_pv->first_pv = 0;
                    $group_pv->new_pv = 0;
                    $group_pv->save();

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $account = $this->getAccount();

        $this->assign('account',$account);

        return $this->view->fetch();
    }


    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $result = $row->save($params);
                    if ($result === false) {
                        exception($row->getError());
                    }

                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        $order_money = 0;
        $this->view->assign("order_money", $order_money);
        $group = UsersGroupModel::get($row->group_id);
        $this->view->assign("group_name", $group?$group->group_name:'');
        $contact = UsersModel::get($row->contact_id);
        $parent = UsersModel::get($row->parent_id);
        $this->view->assign("contact", $contact);
        $this->view->assign("parent", $parent);
        return $this->view->fetch();
    }

    public function childlist()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        $ids = input('ids',0);
        $row = Share::get($ids);
        $this->assignconfig('parent_id',$row->user_id);
        return $this->view->fetch();

    }

    public function rechargeintegral($ids = 'null')
    {
        $ids = input('ids',0);
        $integral = input('integral',0);

        $user = \app\admin\model\usermanage\Users::get($ids);
        $integralLog = new IntegralLog();
        $integralLog->user_id = $user->id;
        $register = new Register();
        $register->user_id = $user->id;
        $register->register_time = '..';
        $register->continuation = 0;
        $register->setAttr('type',3);
        $register->integral = $integral;
        $register->save();
        if (!$user) {
            $this->error('用户不存在，或已删除');
        }
        if (empty($integral)) {
            $this->error('积分设置不正确');
        }

        if ($integral < 0) {
            if ($integral > $user->integral) {
                $this->error('用户当前积分不足');
            }
            $user->integral -= abs($integral);

        } else {
            $user->integral += $integral;
            $user->total_integral += $integral;
        }
        if (!$user->save()) {

            $this->error('操作失败！请重试');
        }
        if ($integral < 0) {
            $integralLog->content = "管理员： 后台操作账号：" . $user->nickname . " 积分扣除：" . $integral . " 积分";
        } else {
            $integralLog->content = "管理员：  后台操作账号：" . $user->nickname . " 积分充值：" . $integral . " 积分";
        }

        $integralLog->integral = $integral;
        $integralLog->username = trim($user->nickname) ? $user->nickname : '未知';
        if ($integralLog->save()) {
            $this->success('操作成功');
        } else {

            $this->error('操作失败');
        }
    }
}
